package com.zte.shopping.action.frontend;

import com.zte.shopping.action.backend.BackendProductManagerController;
import com.zte.shopping.constant.DictConstant;
import com.zte.shopping.constant.ResponseCodeConstant;
import com.zte.shopping.entity.Attache;
import com.zte.shopping.entity.User;
import com.zte.shopping.service.AttacheService;
import com.zte.shopping.service.UserService;
import com.zte.shopping.util.ResponseResult;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type.Int;

/**
 * @program: ssm
 * @description: 个人中心
 * @author: zuti
 * @create: 2020-06-30 18:07
 **/
@Controller
@RequestMapping("center")
public class FrontCenterController {

    @Autowired
    UserService userService;

    @Autowired
    AttacheService attacheService;

    private  static  final Logger logger= Logger.getLogger(FrontCenterController.class);

    /**
     * 进入会员中心
     */
    @RequestMapping("/showCenter")
    public ModelAndView showCenter(HttpSession session)
    {
        ModelAndView modelAndView = new ModelAndView();
        List<Attache> lifeImgs = attacheService.findLifeImageByUserId(session);
//        // 查询当前会员的头像
//        Attache headImg = attacheService.findHeadImageByUserId(session);
//
//
//
//        modelAndView.addObject("headImg", headImg);
        modelAndView.addObject("lifeImgs", lifeImgs);
        modelAndView.setViewName("/frontend/center");

        return modelAndView;
    }

    /**
     * (前台) 个人中心 根据会员id 修改会员 基本资料(会员的联系电话以及联系地址 )
     */
    @RequestMapping("/modifyUser")
    public String modifyUser(String userId, String phone, String address, HttpSession session)
    {
        userService.modifyUser(userId, phone, address);

        User user = (User)session.getAttribute("user");

        user.setPassword(address);
        user.setPhone(phone);

        return "redirect:/center/showCenter";
    }



    /**
     * 上传/修改 用户头像
     * 判断改用户是否拥有头像
     * 若该用户尚未上传头像,则为添加
     * 若该用户已经上传头上,则为修改
     */
    @RequestMapping("/modifyHeadImage")
    public ModelAndView modifyHeadImage(@RequestParam("file") CommonsMultipartFile file, HttpSession session)
    {
        ModelAndView modelAndView = new ModelAndView();

        try
        {
            // 修改用户头像
            attacheService.modifyHeadImage(file, session);
        } catch (Exception e)
        {
            e.printStackTrace();
        }

        modelAndView.setViewName("redirect:/center/showCenter");

        return modelAndView;
    }

    /**
     * 上传 生活照片(支持多张)
     */
    @RequestMapping("/uploadLifeImage")
    public ModelAndView uploadLifeImage(@RequestParam("file") CommonsMultipartFile[] files,
                                        HttpSession session)
    {
        ModelAndView modelAndView = new ModelAndView();

        User user = (User)session.getAttribute("user");


        try
        {
            for (CommonsMultipartFile file : files)
            {
                String path = "/upload/" + new SimpleDateFormat("yyyyMMdd").format(new Date());

                String originalFilename = file.getOriginalFilename();
                String realPath = session.getServletContext().getRealPath(path);

                logger.debug(" FrontCenterController========》uploadLifeImage path="+path
                        +" originalFileName"+originalFilename+"realPath="+realPath);

				// "1.jpg"  ---> 1
			    // substring(int beginIndex, int endIndex)  [beginIndex,endIndex)

                int  weizhi =  originalFilename.lastIndexOf(".");
			    String prefix = originalFilename.substring(0, originalFilename.lastIndexOf("."));

			    // "1.jpg"  ---> .jpg
			    String suffix = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());


			    // 生成UUID, 保证文件名不会重复
			    String uuid = UUID.randomUUID().toString();
			    String fileNameOnly = prefix + uuid + suffix;

				logger.debug(" FrontCenterController========》uploadLifeImage path="+path+" originalFileName"+originalFilename
                        +"fileNameOnly"+fileNameOnly);

                Attache attache = new Attache();
                attache.setCreateDate(new Date());
                attache.setFileType(DictConstant.ATTACHE_FILE_TYPE_LIFE_IMAGE);
                attache.setUser(user);
                attache.setFilePath(path + "/" + fileNameOnly);

                attacheService.addAttache(attache);

                File f = new File(realPath);
                f.mkdirs();

                file.transferTo( new File(realPath, fileNameOnly) );
            }

        } catch (IllegalStateException e)
        {
            modelAndView.addObject("msg",e.getMessage());
        } catch (IOException e)
        {
            modelAndView.addObject("msg",e.getMessage());
        } catch (Exception e)
        {
            e.printStackTrace();
            modelAndView.addObject("msg","服务器内部异常");
        }


        modelAndView.setViewName("redirect:/center/showCenter");

        return modelAndView;
    }



    @ResponseBody
    @RequestMapping(value = "/deleteImg")
    public ResponseResult deleteImg(@RequestParam("imgPath") String imgPath,
                                    @RequestParam("userId")Integer userId)
    {
        ResponseResult result = new ResponseResult();
        try
        {  if(imgPath!=null && imgPath!=""&&userId!=null ) {
            attacheService.deleteImg(imgPath, userId);
            result.setMessage("成功");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);
            }else{
            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        }
        } catch (Exception e)
        {
            e.printStackTrace();
            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);

        }
        return result;
    }


}
